import router, { asyncRoutes, constantRoutes } from '@/router'
import { getMemu } from '@/api/user'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

function routerCom(path) {
  if (path === 'Layout') {
    return Layout
  }else{
    return resolve => require.ensure([], () => resolve(require('@/views' + path)))
  }jjhhhgg
}

function getRoutes(routes,menuNode) {
  routes.forEach(item =>{
    const childrenNode = {
      path: item.path,
      component: routerCom(item.component),
      name: item.name,
      meta: item.meta
    }
    if (menuNode.children) {
      menuNode.children.push(childrenNode)
    } else {
      menuNode.children = []
      menuNode.children.push(childrenNode)
    }

    if(item.children){
      getRoutes(item.children,childrenNode)
    }
  })
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  res.push(getRoutes(routes))
  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles){
    return new Promise((resolve, reject) => {
      getMemu(state.token).then(response => {
        let accessedRoutes = []
        const { data } = response
        if (!data) {
          reject('当前用户没有任何权限')
        }
        data.forEach(item =>{
          const menuNode = {
            path: item.path,
            component: routerCom(item.component),
            redirect: item.redirect,
            name: item.name,
            meta: item.meta
          }
          if(item.children){
            getRoutes(item.children,menuNode)
          }
          accessedRoutes.push(menuNode)
        })
        commit('SET_ROUTES', accessedRoutes)
        resolve(accessedRoutes)
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
